﻿<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>Entities</title>
<link type="text/css" rel="stylesheet" href="bootstrap.min.css" />
</head>

<body>

<!-- START OF THE ARTICLE -->

<ul class="download">
	<li><a href="SimpleTaskSystem.zip">Download sample application</a> (or see on <a href="https://github.com/aspnetboilerplate/aspnetboilerplate-samples">Github</a>)</li>
</ul>

<p><a href="taskever.png"><img alt="Taskever - Made with ASP.NET Boilerplate" border="0" src="taskever.png" style="max-width: 100%;" /></a></p>

<p><i>A comprehensive application made using <strong>ASP.NET Boilerplate</strong>. See <a href="http://www.taskever.com" target="_blank">http://www.<b>taskever</b>.com</a></i></p>

<h2>Contents</h2>

<ul>
	<li><a href="#Introduction">Introduction to the problem</a></li>
	<li><a href="#WhatIsAbp">What is ASP.NET Boilerplate</a></li>
	<li><a href="#WhatAbpIsNot">What ASP.NET Boilerplate is not</a></li>
	<li><a href="#GettingStarted">Getting started</a></li>
	<li><a href="#CreateEmptyApp">Creating empty web application from template</a></li>
	<li><a href="#DomainLayer">Domain Layer</a>
	<ul>
		<li><a href="#DomainEntities">Entities</a></li>
		<li><a href="#DomainRepositories">Repositories</a></li>
		<li><a href="#AboutNamespaces">About namespaces</a></li>
	</ul>
	</li>
	<li><a href="#InfrastructureLayer">Infrastructure Layer</a>
	<ul>
		<li><a href="#InfraMigrations">Database migrations</a></li>
		<li><a href="#InfraMappings">Entity mappings</a></li>
		<li><a href="#InfraRepositoris">Repository implementations</a></li>
	</ul>
	</li>
	<li><a href="#AppLayer">Application Layer</a>
	<ul>
		<li><a href="#AppServices">Application services and Data Transfer Objects (DTOs)</a></li>
		<li><a href="#DTOValidation">DTO validation</a></li>
		<li><a href="#AppWebApi">Dynamic Web API Controllers</a></li>
	</ul>
	</li>
	<li><a href="#PresentationLayer">Presentation Layer</a>
	<ul>
		<li><a href="#PresentSpa">Single page applications</a></li>
		<li><a href="#PresentViewModels">Views and ViewModels</a>
		<ul>
			<li><a href="#PresentTaskList">Task list</a></li>
			<li><a href="#PresentNewTask">New task</a></li>
		</ul>
		</li>
		<li><a href="#Localization">Localization</a></li>
		<li><a href="#JavascriptApi">Javascript API</a></li>
	</ul>
	</li>
	<li><a href="#ArticleMore">More</a>
	<ul>
		<li><a href="#AbpModuleSystem">Module System</a></li>
		<li><a href="#DependencyInjection">Dependency Injection and conventions</a></li>
	</ul>
	</li>
	<li><a href="#AboutAngularSample">About Angularjs &amp; EntityFramework sample</a></li>
	<li><a href="#ArticleSummary">Summary</a></li>
	<li><a href="#ArticleHistory">Article history</a></li>
	<li><a href="#References">References</a></li>
</ul>

<h2 id="Introduction">Introduction to the problem</h2>

<p><strong>DRY </strong>- Don&#39;t Repeat Yourself! is one of the main ideas of a good developer while developing a software. We&#39;re trying to implement it from simple methods to classes and modules. What about developing a new web based application? We, software developers, have similar needs when developing enterprise web applications.</p>

<p><strong>Enterprise web applications</strong> need login pages, user/role management infrastructure, user/application setting management, localization and so on. Also, a high quality and large scale software implements <strong>best practices</strong> such as <strong>Layered Architecture</strong>, <strong>Domain Driven Design</strong> (DDD), <strong>Dependency Injection</strong> (DI). Also, we use <strong>tools</strong> for <strong>Object-Releational Mapping </strong>(ORM), <strong>Database Migrations</strong>, <strong>Logging</strong>... etc. When it comes to the <strong>User Interface</strong> (UI), it&#39;s not much different.</p>

<p>Starting a new enterprise web application is a hard work. Since all applications need some common tasks, we&#39;re repeating ourselves. Many companies are developing their own <strong>Application Frameworks or Libraries</strong> for such common tasks to do not re-develop same things. Others are <strong>copying</strong> some parts of existing applications and preparing <strong>a start point</strong> for their new application. First approach is pretty good if your company is big enough and has time to develop such a framework.</p>

<p>As a software architect, I also developed such a framework im my company. But, there is some point it feels me bad: Many company repeats same tasks. What if we can <strong>share more, repeat less</strong>? What if DRY principle is implemented <strong>universally</strong> instead of per project or per company? It sounds utopian, but I think there may be a starting point for that!</p>

<h2 id="WhatIsAbp">What is ASP.NET Boilerplate?</h2>

<p>ASP.NET Boilerplate [1] is a starting point for new modern web applications using <strong>best practices </strong>and <strong>most popular tools</strong>. It&#39;s aimed to be a <strong>solid model</strong>, a general-purpose <strong>application framework</strong> and a <strong>project template</strong>. What it does?</p>

<ul>
	<li>Server side
	<ul>
		<li>Based on latest <strong>ASP.NET MVC </strong>and <strong>Web API</strong>.</li>
		<li>Implements <strong>Domain Driven Design </strong>(Entities, Repositories, Domain Services, Application Services, DTOs, Unif Of Work... and so on)</li>
		<li>Implements <strong>Layered Architecture </strong>(Domain, Application, Presentation and Infrastructure Layers).</li>
		<li>Provides an infrastructure to develop reusable and composable <strong>modules </strong>for large projects.</li>
		<li>Uses most popular <strong>frameworks/libraries </strong>as (probably) you&#39;re already using.</li>
		<li>Provides an infrastructure and make it easy to use <strong>Dependency Injection </strong>(uses Castle Windsor as DI container).</li>
		<li>Provides a strict model and base classes to use <strong>Object-Releational Mapping </strong>easily (Directly supports EntityFramework and NHibernate).</li>
		<li>Supports and implements <strong>database migrations</strong>.</li>
		<li>Includes a simple and flexible <strong>localization </strong>system.</li>
		<li>Includes an <strong>EventBus </strong>for server-side global domain events.</li>
		<li>Manages <strong>exception handling</strong> and <strong>validation</strong>.</li>
		<li>Creates <strong>dynamic Web API layer </strong>for application services.</li>
		<li>Provides <strong>base and helper classes </strong>to implement some common tasks.</li>
		<li>Uses <strong>convention </strong>over configuration principle.</li>
	</ul>
	</li>
	<li>Client side
	<ul>
		<li>Provides <strong>project templates</strong> for <strong>Single-Page Applications (</strong>with <strong>AngularJs</strong> and <strong>Durandaljs</strong>) and <strong>Multi-Page Applications</strong>. Templates are based on Twitter <strong>Bootstrap</strong>.</li>
		<li>Mostly used javascript libraries are included ana configured by default.</li>
		<li>Creates <strong>dynamic javascript proxies</strong> to call application services (using dynamic Web API layer) easily.</li>
		<li>Includes <strong>unique APIs </strong>for some sommon tasks: showing alerts &amp; notifications, blocking UI, making AJAX requests...</li>
	</ul>
	</li>
</ul>

<p>Beside these common infrastructure, a module named <a href="https://github.com/aspnetboilerplate/module-zero">zero</a> is being developed. It will provide a role and permission based <strong>authorization</strong> system (implementing latest ASP.NET Identity Framework), a <strong>setting</strong> system, <strong> multi-tenancy</strong> and so on.</p>

<h2 id="WhatAbpIsNot">What ASP.NET Boilerplate is not?</h2>

<p>ASP.NET Boilerplate provides an application development model with best practices. It has base classes, interfaces and tools those make easy to build maintainable large-scale applications. But..</p>

<ul>
	<li>It&#39;s not one of RAD (Rapid Application Development) tools those try to provide infrastructure for building applications without coding. Instead, it provides an infrastructure to code in best practices.</li>
	<li>It&#39;s not a code generation tool. While it has several features those build dynamic code in run-time, it does not generate codes.</li>
	<li>It&#39;s not a all-in-one framework. Instead, it uses well known tools/libraries for specific tasks (like NHibernate and EntityFramework for O/RM, Log4Net for logging, Castle Windsor as DI container, AngularJs for SPA framework).</li>
</ul>

<h2 id="GettingStarted">Getting started</h2>

<p>In this article, I&#39;ll show how to deleveop a <strong>Single-Page and Responsive Web Application </strong>using ASP.NET Boilerplate (I&#39;ll call it as <strong>ABP </strong>from now). I will use <strong>DurandalJs</strong> as SPA framework and <strong>NHibernate</strong> as ORM framework here. I prepared <a href="http://www.codeproject.com/Articles/791740/Using-AngularJs-ASP-NET-MVC-Web-API-and-EntityFram"> another article</a> that implements same application with <strong>AngularJs</strong> and <strong>EntityFramework</strong>.</p>

<p>This sample application is named as &quot;<strong>Simple Task System</strong>&quot; and it consists of two pages: one for <strong>list of tasks</strong>, other one is to <strong>add new task</strong>. A Task can be related to a Person, can be active or completed. The application is localized in two languages. Screenshot of Task List in the application is shown below:</p>

<p><img alt="A screenshot of 'Simple Task System'" height="263" src="tasksystem.png" width="596" /></p>

<h2 id="CreateEmptyApp">Creating empty web application from template</h2>

<p>ABP provides <strong>a startup template</strong> for new projects (Even if you can manually create your project and get ABP packages from nuget, template way is much more easy). Go to <a href="http://www.aspnetboilerplate.com/Templates" target="_blank"><strong>www.aspnetboilerplate.com/Templates</strong></a> to create your application from template. You can choice SPA (Single-Page Application) project with optionally AngularJs or DurandalJs. Or you can choice MPA (classic, Multi-Page Application) project. Then you can choice EntityFramework or NHibernate for as ORM framework.</p>

<p><img alt="Creating template from ABP web site" height="370" src="create_template_v2.png" width="590" /></p>

<p>I named my project as <strong>SimpleTaskSystem</strong> and created a <strong>SPA</strong> project with Durandal and NHibernate. Downloaded project as a <strong>zip</strong> file. When I open the zip file, I see a solution is ready that contains assemblies (projects) for each layer of <strong>Domain Driven Design</strong>:</p>

<p><img alt="Project files" height="172" src="project_files2.png" width="195" /></p>

<p>Created project&#39;s runtime is <strong>.NET Framework 4.5.1</strong>, I advice to open with <strong>Visual Studio 2013</strong>. The only prerequise to be able to run the project is to create a <strong>database</strong>. SPA template assumes that you&#39;re using <strong>SQL Server 2008 or later</strong>. But you can change it easily to another DBMS. See the connection string in web.config file of the web project:</p>

<pre lang="xml">
&lt;add name=&quot;Default&quot; connectionString=&quot;Server=localhost; Database=<strong>SimpleTaskSystemDb</strong>; Trusted_Connection=True;&quot; /&gt;</pre>

<p>You can change connection string here. I don&#39;t change the database name, so I&#39;m creating an empty database, named <strong>SimpleTaskSystemDb</strong>, in SQL Server:</p>

<p><img alt="Empty database" height="200" src="empty_db.png" width="174" /></p>

<p><strong>That&#39;s it</strong>, your project is ready to run! Open it in VS2013 and press F5:</p>

<p><img alt="First run" height="199" src="first_run.png" width="596" /></p>

<p>Template consists of two pages: One for <strong>Home </strong>page, other is <strong>About</strong> page. It&#39;s <strong>localized </strong>in English and Turkish. And it&#39;s <strong>Single-Page Application</strong>! Try to navigate between pages, you&#39;ll see that only the contents are changing, navigation menu is fixed, all scripts and styles are loaded only once. And it&#39;s <strong>responsive.</strong> Try to change size of the browser.</p>

<p>Now, I&#39;ll show how to change the application to a Simple Task System application <strong>layer by layer</strong>.</p>

<h2 id="DomainLayer">Domain layer</h2>

<p>&quot;<em>Responsible for representing concepts of the business, information about the business situation, and business rules</em>&quot; (Eric Evans) [2]. In the Domain Driven Design (<strong>DDD</strong>), the core layer is the <strong>Domain Layer</strong>. Domain Layer defines your <strong>Entities,</strong> implements your <strong>business rules </strong>and so on.</p>

<h3 id="DomainEntities">Entities</h3>

<p>Entities are one of the core concepts of DDD. Eric Evans describe it as &quot;<em>An object that is not fundamentally defined by its attributes, but rather by a thread of continuity and identity</em>&quot;. So, entities have Id&#39;s and stored in a database.</p>

<p>My first entity is the <strong>Task</strong>:</p>

<pre lang="cs">
public class Task : Entity&lt;long&gt;
{
    public virtual Person AssignedPerson { get; set; }

    public virtual string Description { get; set; }

    public virtual DateTime CreationTime { get; set; }

    public virtual TaskState State { get; set; }

    public Task()
    {
        CreationTime = DateTime.Now;
        State = TaskState.Active;
    }
}</pre>

<p>It&#39;s simple class derived from <strong>Entity</strong> base class with <strong>long</strong> primary key type. <strong>TaskState</strong> is an enum that has membes as &#39;<strong>Active</strong>&#39; and &#39;<strong>Completed</strong>&#39;. Second entity is the <strong>Person</strong>:</p>

<pre lang="cs">
public class Person : Entity
{
    public virtual string Name { get; set; }
}</pre>

<p>A task has a relation to a person and that&#39;s all for this simple application.</p>

<p>Entities implements <strong>IEntity&lt;TPrimaryKey&gt;</strong> interface in ABP. So, if type of your primary key is long for an Entity, it must implement <strong>IEntity&lt;long&gt;</strong>. If your Entity&#39;s primary key is <strong>int</strong>, you may not define primary key type and directly implement <strong>IEntity</strong> interface. In practice, you can easily derive from <strong>Entity </strong>or <strong>Entity&lt;TPrimaryKey&gt; </strong>classes as shown above (Task and Person). IEntity defines <strong>Id </strong>property for the Entity.</p>

<h3 id="DomainRepositories">Repositories</h3>

<p>&quot;<em>Mediates between the domain and data mapping layers using a collection-like interface for accessing domain objects</em>&quot; (Martin Fowler) [3]. Repositories, in practice, are used to perform database operations for domain objects (Entities or Value Types).</p>

<p>Generally, a seperated repository is used for each Entity (or Aggregate Root). 
ASP.NET Boilerplate provides default repositories for each entity (we will see 
how to use default repositories). If we need to 
define additional methods, we can extend IRepository interface. I extended it for Task 
repository:</p>

<pre lang="cs">
public interface ITaskRepository : IRepository&lt;Task, long&gt;
{
    List&lt;Task&gt; GetAllWithPeople(int? assignedPersonId, TaskState? state);
}</pre>

<p>It&#39;s good to define an interface for each Repository. Thus, we can <strong>seperate interface from implementation</strong>.
<strong>IRepository</strong> interface defines most-common methods for repositories:</p>

<p><img alt="Repository interface" height="385" src="repository_interface2.png" width="460" /></p>

<p>It defines basic <strong>CRUD </strong>methods. So, all repositories are automatically implement all these methods. In addition to standard base methods, you can add methods specific to this repository, as I defined <strong>GetAllWithPeople</strong> method.</p>

<h3 id="AboutNamespaces">About namespaces</h3>

<p>When you investigate source code of the sample application, you&#39;ll see that classes packaged by intention and domain, related classes/interfaces/enums are in same namespace instead of packaging by infrastructure. I would place <strong>Task </strong>class to TaskSystem.Entities namespace, <strong>ITaskRepository </strong>to TaskSystem.Repositories namespace, <strong> TaskState </strong>to TaskSystem.Enums namespace and so on... Instead, I placed all of these classes to <strong>TTaskSystem.Tasks </strong>namespace since all of these are related to each other. This is more appropriate to nature of Domain Driven Design. So, I think it&#39;s not a good practice to place all Entities to TaskSystem.Entities namespace. Some of you may not think like that. I can understand they since I was doing it like that until short time ago. But I did see the problems and I strongly advice to place related classes/interfaces/enums to same namespace, maybe different assemblies but the same namespace. You can read &quot;The pitfalls of Infrastructure-Driven Packaging&quot; section of Domain Driven Design [2] book of Eric Evans.</p>

<h2 id="InfrastructureLayer">Infrastructure layer</h2>

<p>&quot;<em>Provides generic technical capabilities that support the higher layers</em>&quot; (Eric Evans). It&#39;s used to implement abstractions of your application using third-party libraries &amp; frameworks such as Object-Relational Mapping. In this application, I&#39;ll use Infrastructure Layer for:</p>

<ul>
	<li>Creating database migration system using <strong>FluentMigrator</strong>.</li>
	<li>Implementing Repositories and mapping Entities with <strong>NHibernate</strong> and <strong>FluentNHibernate</strong>.</li>
</ul>

<h3 id="InfraMigrations">Database Migrations</h3>

<p>&quot;<em><strong>Evolutionary Database Design</strong>: Over the last few years we&#39;ve developed a number of techniques that allow a database design to evolve as an application develops. This is a very important capability for agile methodologies.</em>&quot; Martin Fowler says in his web site [3]. Database migration is an important technique to support this idea. It&#39;s very hard to maintain an application&#39;s database in more than one production environment without such techniques. Even if you&#39;ve only one live system, it&#39;s critical.</p>

<p><strong>FluentMigrator</strong> [4] is a good tool for database migrations. It supports most common database systems. Here, my migration codes for <strong>Person </strong>and <strong>Task </strong>tables.</p>

<pre lang="cs">
[Migration(2014041001)]
public class _01_CreatePersonTable : AutoReversingMigration
{
    public override void Up()
    {
        Create.Table(&quot;StsPeople&quot;)
            .WithColumn(&quot;Id&quot;).AsInt32().Identity().PrimaryKey().NotNullable()
            .WithColumn(&quot;Name&quot;).AsString(32).NotNullable();

        Insert.IntoTable(&quot;StsPeople&quot;)
            .Row(new { Name = &quot;Douglas Adams&quot; })
            .Row(new { Name = &quot;Isaac Asimov&quot; })
            .Row(new { Name = &quot;George Orwell&quot; })
            .Row(new { Name = &quot;Thomas More&quot; });
    }
}

[Migration(2014041002)]
public class _02_CreateTasksTable : AutoReversingMigration
{
    public override void Up()
    {
        Create.Table(&quot;StsTasks&quot;)
            .WithColumn(&quot;Id&quot;).AsInt64().Identity().PrimaryKey().NotNullable()
            .WithColumn(&quot;AssignedPersonId&quot;).AsInt32().ForeignKey(&quot;TsPeople&quot;, &quot;Id&quot;).Nullable()
            .WithColumn(&quot;Description&quot;).AsString(256).NotNullable()
            .WithColumn(&quot;State&quot;).AsByte().NotNullable().WithDefaultValue(1) //1: TaskState.New
            .WithColumn(&quot;CreationTime&quot;).AsDateTime().NotNullable().WithDefault(SystemMethods.CurrentDateTime);
    }
}
</pre>

<p>In FluentMigrator, a migration is defined in a class derived from <strong>Migration</strong>. <strong>AutoReversingMigration </strong>is a shortcut if your migration can be automatically rolled back. A migration class should has <strong>MigrationAttribute</strong>. It defines <strong>version number </strong>of the migration class. All migrations are applied ordered by this version number. It can be any <strong>long </strong>number. I use a number that identify the migration class&#39;s creation date plus an incremental value for same day (Example: for second migration class in 24 April 2014, version is &#39;2014042402&#39;). It&#39;s completely up to you. Only important thing is their relative order.</p>

<p>FluentMigrator stores latest applied version number in a table in the database. So, it applies only migrations those are bigger than the version of the database. By default, it uses &#39;VersionInfo&#39; table. If you want to change the table name, you can create such a class:</p>

<pre lang="cs">
[VersionTableMetaData]
public class VersionTable : DefaultVersionTableMetaData
{
    public override string TableName
    {
        get
        {
            return &quot;StsVersionInfo&quot;;
        }
    }
}</pre>

<p>As you see, I write a prefix <strong>Sts</strong> (<strong>S</strong>imple <strong>T</strong>ask <strong>S</strong>ystem) for all tables. That is important for a modular application so all modules can have their specific prefix to identify the module-specific tables.</p>

<p>To create my tables in the database, I use <strong>Migrate.exe </strong>tool of FluentMigrator with such a &#39;<strong>command line</strong>&#39; command:</p>

<pre>
Migrate.exe /connection &quot;Server=localhost; Database=SimpleTaskSystemDb; Trusted_Connection=True;&quot; /db sqlserver /target &quot;SimpleTaskSystem.Infrastructure.NHibernate.dll&quot;</pre>

<p>For a shortcut, ABP template includes <strong>RunMigrations.bat </strong>file. After I compile the project in <strong>Debug </strong>mode, I run the &quot;RunMigrations.bat&quot;:</p>

<p><img alt="Database migrations" height="598" src="migration.png" width="596" /></p>

<p>As you see, two migration files are executed and tables are created:</p>

<p><img alt="Database after migrations" height="148" src="db_after_migration.png" width="188" /></p>

<p>For more information on FluentMigrator, see it&#39;s web site [4].</p>

<h3 id="InfraMappings">Entity mappings</h3>

<p>In order to get/store Entities into database, we should map Entities with database tables. NHibernate has several options to accomplish that. Here, I&#39;ll use manual <strong>Fluent Mapping </strong>(You can use conventional auto-mapping, see <strong>FluentNHibernate</strong>&#39;s web site [5]):</p>

<pre>
public class PersonMap : EntityMap&lt;Person&gt;
{
    public PersonMap()
        : base(&quot;StsPeople&quot;)
    {
        Map(x =&gt; x.Name);
    }
}
    
public class TaskMap : EntityMap&lt;Task, long&gt;
{
    public TaskMap()
        : base(&quot;StsTasks&quot;)
    {
        Map(x =&gt; x.Description);
        Map(x =&gt; x.CreationTime);
        Map(x =&gt; x.State).CustomType&lt;TaskState&gt;();
        References(x =&gt; x.AssignedPerson).Column(&quot;AssignedPersonId&quot;).LazyLoad();
    }
}
</pre>

<p><strong>EntityMap</strong> is a class of ABP that automatically maps <strong>Id </strong>property and gets <strong>table name </strong>in the constructor. So, I&#39;m deriving from it and mapping other properties.</p>

<h3 id="InfraRepositoris">Repository implementations</h3>

<p>I defined interface for Task repository (ITaskRepository) in the domain layer. Here, I&#39;ll implement 
it here in NHibernate:</p>

<pre>
public class TaskRepository : NhRepositoryBase&lt;Task, long&gt;, ITaskRepository
{
    public List&lt;Task&gt; GetAllWithPeople(int? assignedPersonId, TaskState? state)
    {
        //In repository methods, we do not deal with create/dispose DB connections (Session) and transactions. ABP handles it.
            
        var query = GetAll(); //GetAll() returns IQueryable&lt;T&gt;, so we can query over it.
        //var query = Session.Query&lt;Task&gt;(); //Alternatively, we can directly use NHibernate&#39;s Session
            
        //Add some Where conditions...

        if (assignedPersonId.HasValue)
        {
            query = query.Where(task =&gt; task.AssignedPerson.Id == assignedPersonId.Value);
        }

        if (state.HasValue)
        {
            query = query.Where(task =&gt; task.State == state);
        }

        return query
            .OrderByDescending(task =&gt; task.CreationTime)
            .Fetch(task =&gt; task.AssignedPerson) //Fetch assigned person in a single query
            .ToList();
    }
}</pre>

<p><strong>NhRepositoryBase </strong>implements all methods those are defined in <strong>IRepository </strong>interface. So, you must only implement your custom methods as I implemented for <strong>GetAllWithPeople</strong>.</p>
<p><strong>GetAll()</strong> method returns <strong>IQueryable&lt;TEntity&gt;</strong>, so you can write additional conditions until invoke <strong>ToList()</strong>.</p>

<p>No need to define or implement a repository for an entity if standard 
repository methods are enough for this entity. So, I did not implemented 
repository for Person entity.</p>

<h2 id="AppLayer">Application layer</h2>

<p>&quot;<em>Defines the jobs the software is supposed to do and directs the expressive domain objects to work out problems</em>&quot; (Eric Evans). Application layer does not include domain information and business rules in an ideal application (this may not be possible in the real life but we should minimize it). It mediates between presentation layer and domain layer.</p>

<h3 id="AppServices">Application services and Data Transfer Objects (DTOs)</h3>

<p>Application services provide the functionality of the application layer. An application service method gets data transfer objects as arguments and returns a data transfer object. Directly returning Entities (or other domain object) has many problems (Like data hiding, serialization and lazy loading problems). I strongly recommend to not get/return Entities or any other domain objects from application services. They should only ger/return DTOs. Thus, Presentation layer is completely isolated from Domain layer.</p>

<p>So, let&#39;s start from easy one, person application service:</p>

<pre>
public interface IPersonAppService : <strong>IApplicationService</strong>
{
    GetAllPeopleOutput GetAllPeople();
}</pre>

<p>All application services implement <strong>IApplicationService </strong>by convention. It ensures <strong>dependency injection </strong>and provides some built-in features of ABP (like validation). I defined only one method, named <strong>GetAllPeople()</strong> and returns a DTO named <strong>GetAllPeopleOutput</strong>. I name DTOs as like that: <strong>method name </strong>plus <strong>Input </strong>or <strong>Output </strong>postfix. See <strong>GetAllPeopleOutput </strong>class:</p>

<pre>
public class GetAllPeopleOutput : IOutputDto
{
    public List&lt;PersonDto&gt; People { get; set; }
}</pre>

<p>An output DTO implements <strong>IOutputDto</strong> (it extends IDto). It does nothing but used to identify DTOs by convention. <strong>PersonDto </strong>is another DTO class to pass a <strong>Person </strong>information to the presentation layer:</p>

<pre>
public class PersonDto : EntityDto
{
    public string Name { get; set; }
}</pre>

<p><strong>EntityDto </strong>is another helper class of ABP that defines <strong>Id </strong>property and implements <strong>IDto </strong>interface automatically. <strong>IPersonAppService</strong> is implemented as shown below:</p>

<pre>public class PersonAppService : IPersonAppService //Optionally, you can derive from ApplicationService as we did for TaskAppService class.
{
    private readonly IRepository&lt;Person&gt; _personRepository;

    //ABP provides that we can directly inject IRepository&lt;Person&gt; (without creating any repository class)
    public PersonAppService(IRepository&lt;Person&gt; personRepository)
    {
        _personRepository = personRepository;
    }

    public GetAllPeopleOutput GetAllPeople()
    {
        return new GetAllPeopleOutput
                {
                    People = Mapper.Map&lt;List&lt;PersonDto&gt;&gt;(_personRepository.GetAllList())
                };
    }
}</pre>

<p><strong>PersonAppService </strong>gets <strong>IRepository&lt;Person&gt;</strong> as argument in it&#39;s constructor. ABP&#39;s built-in <strong>dependency injection </strong>system handles it using <strong>Castle Windsor</strong>. All repositories and application services are automatically registered to IOC (Inversion of Control) container as <strong>transient </strong>objects. So, you&#39;re not thinking on DI details. 
Also, ABP can create a standard repository for an entity without defining or 
implementing a repository.</p>

<p><strong>GetAllPeople()</strong> method simply gets a list of all people (using ABP&#39;s out of the box implementation) from database and converts it to list of <strong>PersonDto </strong>objects using <strong>AutoMapper</strong> [6] library. AutoMapper makes it incredibly easy to map one class to another using conventions (and configurations if needed). I just defined a single line of code to configure mapping:</p>

<pre>
Mapper.CreateMap&lt;Person, PersonDto&gt;();</pre>

<p>This code works when application starts and creates mapping. Then, when I need, I call the Mapper.Map method to create a <strong>PersonDto </strong>object using an existing <strong>Person </strong>object. To get more informatin about AutoMapper, see it&#39;s web site [6]. Other application service is <strong>TaskAppService </strong>implemented as below:</p>

<pre>public class TaskAppService : ApplicationService, ITaskAppService
{
    //These members set in constructor using constructor injection.
        
    private readonly ITaskRepository _taskRepository;
    private readonly IRepository&lt;Person&gt; _personRepository;
        
    /// &lt;summary&gt;
    ///In constructor, we can get needed classes/interfaces.
    ///They are sent here by dependency injection system automatically.
    /// &lt;/summary&gt;
    public TaskAppService(ITaskRepository taskRepository, IRepository&lt;Person&gt; personRepository)
    {
        _taskRepository = taskRepository;
        _personRepository = personRepository;
    }
        
    public GetTasksOutput GetTasks(GetTasksInput input)
    {
        //Called specific GetAllWithPeople method of task repository.
        var tasks = _taskRepository.GetAllWithPeople(input.AssignedPersonId, input.State);

        //Used AutoMapper to automatically convert List&lt;Task&gt; to List&lt;TaskDto&gt;.
        return new GetTasksOutput
                {
                    Tasks = Mapper.Map&lt;List&lt;TaskDto&gt;&gt;(tasks)
                };
    }
        
    public void UpdateTask(UpdateTaskInput input)
    {
        //We can use Logger, it&#39;s defined in ApplicationService base class.
        Logger.Info(&quot;Updating a task for input: &quot; + input);

        //Retrieving a task entity with given id using standard Get method of repositories.
        var task = _taskRepository.Get(input.TaskId);

        //Updating changed properties of the retrieved task entity.

        if (input.State.HasValue)
        {
            task.State = input.State.Value;
        }

        if (input.AssignedPersonId.HasValue)
        {
            task.AssignedPerson = _personRepository.Load(input.AssignedPersonId.Value);
        }

        //We even do not call Update method of the repository.
        //Because an application service method is a &#39;unit of work&#39; scope as default.
        //ABP automatically saves all changes when a &#39;unit of work&#39; scope ends (without any exception).
    }

    public void CreateTask(CreateTaskInput input)
    {
        //We can use Logger, it&#39;s defined in ApplicationService class.
        Logger.Info(&quot;Creating a task for input: &quot; + input);

        //Creating a new Task entity with given input&#39;s properties
        var task = new Task { Description = input.Description };

        if (input.AssignedPersonId.HasValue)
        {
            task.AssignedPersonId = input.AssignedPersonId.Value;
        }

        //Saving entity with standard Insert method of repositories.
        _taskRepository.Insert(task);
    }
}</pre>

<p>In the <strong>UpdateTask </strong>method, I&#39;m getting the <strong>Task </strong>Entity from task repository and setting changed properties. <strong>State </strong>or/and <strong>AssignedPersonId </strong>might be changed. Notice that I did not call _taskRepository.<strong>Update</strong> or any other method to save changes to database. Because, an application service method is a <strong>unit of work</strong> as default in ASP.NET Boilerplate. For a unit of work method, it basically opens a <strong>database connection</strong> and begins <strong>transaction</strong> at the beginning of the method and saves all changes (commits the transaction) to database at the end of the method automatically. It <strong>rollbacks</strong> the transaction if an Exception is thrown in the execution of the method. If a <strong>unit of work</strong> method calls another unit of work method, they use the same transaction. First called unit of work method handles connection and transaction management automatically.</p>

<p>To read more about unit of work system in ASP.NET Boilerplate, see <a href="http://www.aspnetboilerplate.com/Pages/Documents/Unit-Of-Work" target="_blank"> documentation</a>.</p>

<h3 id="DTOValidation">DTO Validation</h3>

<p>Validation is an important and critical but a little tedious concept in application development. ABP provides infrastructure to make validation easier and nicer. Validating the user input is an application-layer task. An application service method should validate inputs and throw exceptions if given input is not valid. ASP.NET MVC and Web API has built-in validation system that can be achived using data annotations (like Required). But an Application service is a plain class, not derived from Controller. Fortunately, ABP provides similar mechanism for ordinary application service methods (using Castle Dynamic proxies and interception). Your method&#39;s input parameter should be marked as IValidate. IInputDto is already derived from IValidate, so you can mark your DTO class as IInputDto to enable validation:</p>

<pre lang="cs">
public class CreateTaskInput : IInputDto
{
    public int? AssignedPersonId { get; set; }

    [Required]
    public string Description { get; set; }
}</pre>

<p>In this input DTO, only the Description property is required. ABP automatically checks it before calling the application service method and throws exception if it&#39;s null or empty. All of validation attributes in <strong>System.ComponentModel.DataAnnotations</strong> namespace can be used here. If these standard attributes are not enough for you, you can implement <strong>ICustomValidate</strong>:</p>

<pre lang="cs">
public class CreateTaskInput : IInputDto, ICustomValidate
{
    public int? AssignedPersonId { get; set; }

    public bool SendEmailToAssignedPerson { get; set; }

    [Required]
    public string Description { get; set; }

    public void AddValidationErrors(List&lt;ValidationResult&gt; results)
    {
        if (SendEmailToAssignedPerson &amp;&amp; (!AssignedPersonId.HasValue || AssignedPersonId.Value &lt;= 0))
        {
            results.Add(new ValidationResult(&quot;AssignedPersonId must be set if SendEmailToAssignedPerson is true!&quot;));
        }
    }
}</pre>

<p>One more thing: ABP checks if input parameter of a service method is null. So, you don&#39;t need to write guard clauses for that.</p>

<p>I advice to create seperated input and output classes for each application service method even it has only one input argument. This is good when extending the application by adding other arguments to this method. It provides a way of adding parameters to the application service method without breaking existing clients.</p>

<h3 id="AppWebApi">Dynamic Web API Controllers</h3>

<p>Application services are consumed by Presentation Layer. In a Single-Page application, all datas are sent/received using AJAX between javascript and the server. ABP extremely simplifies calling an application service method from javascript. How it does this? Let me to explain...</p>

<p>An application service can not directly called by javascript. We may use ASP.NET <strong>Web API </strong>to expose services to clients (There are many other frameworks for that such as Web Services, WCF, SignalR and so on). So, there may be such a flow:</p>

<p><img alt="Calling Web API from Javascript using AJAX" height="327" src="calling_webapi_ajax.png" width="270" /></p>

<p>Javascript calls a Web API controller&#39;s action via AJAX, the Web API controller&#39;s action then calls corresponding application service&#39;s method, gets result and returns to the client. This is pretty robotic. ABP automates this and can <strong>dynamically </strong>create a Web API controller for an application service. Here the all code to create Web API controllers for my Application Services: task service and person service:</p>

<pre>DynamicApiControllerBuilder
    .ForAll&lt;IApplicationService&gt;(Assembly.GetAssembly(typeof (SimpleTaskSystemApplicationModule)), &quot;tasksystem&quot;)
    .Build();</pre>

<p>Thus, all methods of task and person application services are exposed to clients using ASP.NET Web API (ABP&#39;s fluent dynamic controller creation API supports hiding a method from Web API 
or selecting specific application services, try it yourself). In the Presentation Layer section, we will see how to call these Web API controllers with ABP&#39;s <strong>dynamic javascript proxies</strong>.</p>

<h2 id="PresentationLayer">Presentation layer</h2>

<p>&nbsp;&quot;<em>Responsible for showing information to the user and interpreting user&#39;s commands</em>&quot; (Eric Evans). The most obvious layer of the DDD is the Presentation Layer since we can see it, we can click it :).</p>

<h3 id="PresentSpa">Single page applications</h3>

<p>Wikipedia says about SPA:</p>

<blockquote>
<p>A single-page application (SPA), also known as single-page interface (SPI), is a web application or web site that fits on a single web page with the goal of providing a more fluid user experience akin to a desktop application.</p>

<p>In an SPA, either all necessary code &ndash; HTML, JavaScript, and CSS &ndash; is retrieved with a single page load, or the appropriate resources are dynamically loaded and added to the page as necessary, usually in response to user actions. The page does not reload at any point in the process, nor does control transfer to another page, although modern web technologies (such as those included in HTML5) can provide the perception and navigability of separate logical pages in the application. Interaction with the single page application often involves dynamic communication with the web server behind the scenes.</p>
</blockquote>

<p>There are many frameworks and libraries those provide an infrastructure to build SPAs. ASP.NET Boilerplate can work with any SPA framework but provides simple infrastructure to work with <strong>DurandalJs</strong> and <strong> AngularJs</strong> easier (See same application <a href="http://www.codeproject.com/Articles/791740/Using-AngularJs-ASP-NET-MVC-Web-API-and-EntityFram" target="_blank"> developed with AngularJs</a>).</p>

<p><strong>Durandal </strong>[7] is one of these frameworks and I think it&#39;s is a very successful open source project. It&#39;s built on successful and mostly used projects: <strong>jQuery</strong> (used for DOM manipulation and AJAX), <strong>knockout.js</strong> (used for MVVM, binding javascript models with HTML) and <strong>require.js</strong> (used to manage javascript dependencies and loading javascript from server dynamically). For more information and rich documentation, visit to Durandal&#39;s web site.</p>

<h3 id="PresentViewModels">Views and ViewModels</h3>

<p>In Durandal, a part of a page consists of a <strong>view </strong>and a <strong>viewmodel</strong>. 
In ABP's startup template, there are three views: <strong>layout</strong>, <strong>home </strong>and <strong>about</strong>. Layout provides menu and container for pages. home and about are views loaded dynamically into page. I changed views and models in order to create my Simple Task System application. After changing views, here the files of all view and viewmodels:</p>

<p>&nbsp; <img alt="Durandal Views for ABP Single Page Application 'Simple Task System'" height="307" src="sts_spa_files2.png" width="239" /></p>

<p>I have a layout and two-views: <strong>task list </strong>and <strong>new task</strong>. Let&#39;s begin to investigate views.</p>

<h4 id="PresentTaskList">Task list</h4>

<p>In the task list, there is a list of all tasks with task description, assigned person and creation date. There is a <strong>combobox</strong> to filter all/avtice/completed tasks. Completed tasks are shown as gray (with an OK icon), active tasks are shown as bold (with a minus icon). The only completed task is the &quot;<em>Complete the Codeproject article!</em>&quot; that&#39;s assigned to me. Thus, you can read this article :)</p>

<p><img alt="A screenshot of 'Simple Task System'" height="263" src="tasksystem.png" width="596" /></p>

<p>Let me to start with the view model. A <strong>ViewModel</strong> is used to communicate with the server to perform user actions (listing tasks, changing combobox, clicking the icon to change status of the task) and provide a model to show in the view.</p>

<pre lang="js">define([&#39;service!tasksystem/task&#39;],
    function (taskService) {

        return function () {
            var that = this; //an alias of this

            that.tasks = ko.mapping.fromJS([]);  //list of tasks

            that.localize = abp.localization.getSource(&#39;SimpleTaskSystem&#39;);

            that.selectedTaskState = ko.observable(0); //&#39;All tasks&#39; option is selected in combobox as default

            that.activate = function () {
                that.refreshTasks();
            };

            that.refreshTasks = function () {
                abp.ui.setBusy( //Set whole page busy until getTasks complete
                    null,
                    taskService.getTasks({
                        state: that.selectedTaskState() &gt; 0 ? that.selectedTaskState() : null
                    }).done(function(data) {
                        ko.mapping.fromJS(data.tasks, that.tasks);
                    })
                );
            };

            that.changeTaskState = function (task) {
                var newState;
                if (task.state() == 1) {
                    newState = 2;
                } else {
                    newState = 1;
                }

                taskService.updateTask({
                    taskId: task.id(),
                    state: newState
                }).done(function () {
                    task.state(newState);
                    abp.notify.info(that.localize(&#39;TaskUpdatedMessage&#39;));
                });
            };
        };
    });</pre>

<p>First line calls require.js&#39;s <strong>define </strong>function to register the module and declare dependencies. A dependency is generally another module (even maybe a view model). &#39;<strong>service!tasksystem/task</strong>&#39; is a special syntax of ABP that reference to the dynamic Web API controller for <strong>task application service</strong> (remember how I defined the task service in Dynamic Web API Controllers section). getTasks function is <strong>dynamically</strong> created by ABP.</p>

<p>Second parameter of define function is the module itself. It should be a function that defines the module. It&#39;s parameters are automatically filled by Durandal using your dependency list.</p>

<p><strong>that.tasks </strong>is a <strong>knockout observable array</strong>. It&#39;s created using <strong>knockout.mapping</strong> function. <strong>that.localize</strong> is a function to be used for localization. It&#39;s a feature of ABP to localize texts dynamically in javascript (Will be detailed in Localization section). <strong>that.selectedTaskState </strong>is an <strong>observable </strong>that is binded to the combobox to show all/active/completed tasks.</p>

<p><strong>activate</strong> is a special function of Durandal. This function is called automatically by Durandal when this view is activated. So, we can write some codes to run when user enters the view.</p>

<p>In the <strong>refreshTasks </strong>method, I called <strong>Task Application Service</strong>&#39;s <strong>getTasks</strong> method to load tasks from server. To call an application service from javascript is that easy through ABP&#39;s dynamic Web API controller and dynamic <strong>javascript client proxies</strong>. getTasks function gets same arguments of <strong>TaskAppService.GetTasks</strong>. The function will return a jQuery <strong>promise</strong>, so you can write a <strong>done </strong>handler to get <strong>return value</strong> the GetTasks method of the task application service. taskService.getTasks also handles errors and shows error message to the user if needed. If the done handler is called, you can be sure that there is no error. In the done handler, I added retrived tasks to the that.task observable array.</p>

<p><strong>changeTaskState </strong>is also pretty similar. It&#39;s used to change a task&#39;s state from <strong>active </strong>to <strong>completed </strong>or vice verse. In the done handler, you can see usages of <strong>localization </strong> and <strong>notification </strong>APIs.</p>

<p>Like a ViewModel is a javascript file, a View is an HTML file. In this HTML file, you can bind ViewModel to HTML elements. ASP.NET Boilerplates moves this one step further by allowing to define Views as <strong>Razor Views</strong>: dynamic <strong>cshtml </strong>files instead of&nbsp; static <strong>html </strong>files. Thus, you can write C# code to create views. See the <strong>tasklist view</strong>:</p>

<pre lang="html">&lt;div class=&quot;panel panel-default&quot;&gt;
    &lt;div class=&quot;panel-heading&quot; style=&quot;position: relative;&quot;&gt;
        &lt;div class=&quot;row&quot;&gt;
            &lt;h3 class=&quot;panel-title col-xs-6&quot;&gt;
                @L(&quot;TaskList&quot;) - &lt;span data-bind=&quot;text: abp.utils.formatString(localize(&#39;Xtasks&#39;), tasks().length)&quot;&gt;&lt;/span&gt;
            &lt;/h3&gt;
            &lt;div class=&quot;col-xs-6 text-right&quot;&gt;
                &lt;select data-bind=&quot;value: selectedTaskState, event: { change: refreshTasks }&quot;&gt;
                    &lt;option value=&quot;0&quot;&gt;@L(&quot;AllTasks&quot;)&lt;/option&gt;
                    &lt;option value=&quot;1&quot;&gt;@L(&quot;ActiveTasks&quot;)&lt;/option&gt;
                    &lt;option value=&quot;2&quot;&gt;@L(&quot;CompletedTasks&quot;)&lt;/option&gt;
                &lt;/select&gt;
            &lt;/div&gt;
        &lt;/div&gt;
    &lt;/div&gt;
    &lt;ul class=&quot;list-group&quot; data-bind=&quot;foreach: tasks&quot;&gt;
        &lt;div class=&quot;list-group-item&quot;&gt;
            &lt;span class=&quot;task-state-icon glyphicon&quot; data-bind=&quot;click: $parent.changeTaskState, css: { &#39;glyphicon-minus&#39;: state() == 1, &#39;glyphicon-ok&#39;: state() == 2 }&quot;&gt;&lt;/span&gt;
            &lt;span data-bind=&quot;html: description(), css: { &#39;task-description-active&#39;: state() == 1, &#39;task-description-completed&#39;: state() == 2 }&quot;&gt;&lt;/span&gt;
            &lt;br /&gt;
            &lt;span data-bind=&quot;visible: assignedPersonId()&quot;&gt;
                &lt;span class=&quot;task-assignedto&quot; data-bind=&quot;text: assignedPersonName&quot;&gt;&lt;/span&gt;
            &lt;/span&gt;
            &lt;span class=&quot;task-creationtime&quot; data-bind=&quot;text: moment(creationTime()).fromNow()&quot;&gt;&lt;/span&gt;
        &lt;/div&gt;
    &lt;/ul&gt;
&lt;/div&gt;</pre>

<p>This view is simply designed to work with Twitter Bootstrap. CSS classes are bootstrap&#39;s classes. But this is not important. There are two important points here:</p>

<p><strong>First</strong>: We can use <strong>@L(&quot;TaskList&quot;)</strong> to get a localized string. <strong>L</strong> method is defined in <strong>AbpWebViewPage</strong> class (See SimpleTaskSystemWebViewPageBase class that is derived from AbpWebViewPage). You can use <strong>L</strong> shortcut of <strong>LocalizationHelper.GetString(...)</strong> in views (See Localization section for details). Since this is a Razor View, we can directly use C# code in the view. Thus, we can create dynamic HTML in the server side. Remember that this View will be loaded only one time since this is a SPA!</p>

<p><strong>Second</strong>: We can use fields of the javascript ViewModel using knockout <strong>data-bind </strong>atribute (like data-bind=&quot;<strong>foreach: tasks</strong>&quot;) and other javascript methods (like <strong>abp.utils.formatString</strong>). Thus, we can create dynamic HTML in the client side. See &quot;<strong>click: $parent.changeTaskState</strong>&quot;, this is used to bind click event of the icon to the <strong>changeTaskState </strong>function in the javascript ViewModel code. As similar, we&#39;re binding <strong>change </strong>event of the <strong>combobox </strong>to <strong>refreshTasks </strong>function. For more information, see <strong>knockout.js</strong> web site.</p>

<h4 id="PresentNewTask">New task</h4>

<p>&quot;New Task&quot; view is relatively simple. There is a task description and an optional person selection:</p>

<p><img alt="New task screen" height="345" src="new_task_screen.png" width="596" /></p>

<p>ViewModel for this page is shown below:</p>

<pre lang="js">define([&#39;service!tasksystem/person&#39;, &#39;service!tasksystem/task&#39;, &#39;plugins/history&#39;],
    function (personService, taskService, history) {

        var localize = abp.localization.getSource(&#39;SimpleTaskSystem&#39;);

        return function () {
            var that = this;

            var _$view = null;
            var _$form = null;

            that.people = ko.mapping.fromJS([]);

            that.task = {
                description: ko.observable(&#39;&#39;),
                assignedPersonId: ko.observable(0)
            };

            that.canActivate = function () {
                return personService.getAllPeople().done(function (data) {
                    ko.mapping.fromJS(data.people, that.people);
                });
            };

            that.attached = function (view, parent) {
                _$view = $(view);
                _$form = _$view.find(&#39;form&#39;);
                _$form.validate();
            };

            that.saveTask = function () {
                if (!_$form.valid()) {
                    return;
                }

                abp.ui.setBusy(_$view,
                    taskService.createTask(ko.mapping.toJS(that.task))
                        .done(function() {
                            abp.notify.info(abp.utils.formatString(localize(&quot;TaskCreatedMessage&quot;), that.task.description()));
                            history.navigate(&#39;&#39;);
                        })
                );
            };
        };
    });</pre>

<p><strong>canActivate </strong>is a special function of Durandal. In this function, you can return true/false to allow/prevent to enter to the page. Durandal also accept a <strong>promise</strong>. In this case, it waits result of the promise to decide to activate the view or not. Your promise should return true/false. ABP overrides this behaviour to accept promises any other data type beside true/false. Thus, we can directly return promises returned from dynamic javascript proxies of ABP (as shown in canActivate method above).</p>

<p><strong>attached</strong> is also another special function of Durandal that is called when your view is attached to DOM (Document Object Model) and safe to manipulate it.</p>

<p><strong>saveTask</strong> is used to save given task to the server. It first validates the form and then calls <strong>taskService.createTask </strong> function (Remember that this function is automatically and dynamically created by ABP and it returns a promise). Here, you see two API calls of ABP. <strong>abp.notify.info</strong> is used to show notifications after save task to the server. <strong>abp.ui.setBusy </strong>is used to set a DOM element as busy (shows loading indicator and blocks the UI element, all view in this case). It accepts a promise and cancels busy when promise returned (either fail or success). ABP uses several jQuery plug-ins for that.</p>

<h3 id="Localization">Localization</h3>

<p>ABP provides a strong and flexible localization system. You can store your localization texts in <strong>resource files</strong>, <strong>XML files</strong> or even in a <strong>custom source</strong>. In this section, I&#39;ll show using XML files. Simple Task System project includes XML files in the Localization folder:</p>

<p><img alt="Localization files" height="127" src="localization_files2.png" width="222" /></p>

<p>Here, the content of the SimpleTaskSystem.xml:</p>

<pre lang="xml">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot; ?&gt;
&lt;localizationDictionary culture=&quot;en&quot;&gt;
  &lt;texts&gt;
    &lt;text name=&quot;TaskSystem&quot; value=&quot;Task System&quot; /&gt;
    &lt;text name=&quot;TaskList&quot; value=&quot;Task List&quot; /&gt;
    &lt;text name=&quot;NewTask&quot; value=&quot;New Task&quot; /&gt;
    &lt;text name=&quot;Xtasks&quot; value=&quot;{0} tasks&quot; /&gt;
    &lt;text name=&quot;AllTasks&quot; value=&quot;All tasks&quot; /&gt;
    &lt;text name=&quot;ActiveTasks&quot; value=&quot;Active tasks&quot; /&gt;
    &lt;text name=&quot;CompletedTasks&quot; value=&quot;Completed tasks&quot; /&gt;
    &lt;text name=&quot;TaskDescription&quot; value=&quot;Task description&quot; /&gt;
    &lt;text name=&quot;EnterDescriptionHere&quot; value=&quot;Task description&quot; /&gt;
    &lt;text name=&quot;AssignTo&quot; value=&quot;Assign to&quot; /&gt;
    &lt;text name=&quot;SelectPerson&quot; value=&quot;Select person&quot; /&gt;
    &lt;text name=&quot;CreateTheTask&quot; value=&quot;Create the task&quot; /&gt;
    &lt;text name=&quot;TaskUpdatedMessage&quot; value=&quot;Task has been successfully updated.&quot; /&gt;
    &lt;text name=&quot;TaskCreatedMessage&quot; value=&quot;Task {0} has been created successfully.&quot; /&gt;
  &lt;/texts&gt;
&lt;/localizationDictionary&gt;</pre>

<p>It's a simple XML file includes name-value pairs for all localizable texts. 
culture attribute defines culture of the file. There is also an XML file for 
Turkish (tr) localization in the solution. Localization files should be 
registered to ABP in order to be usable in the C# and javascript:</p>

<pre lang="cs">Configuration.Localization.Sources.Add(
    new XmlLocalizationSource(
        &quot;SimpleTaskSystem&quot;,
        HttpContext.Current.Server.MapPath(&quot;~/Localization/SimpleTaskSystem&quot;)
        )
    );</pre>

<p>A localization source must be a <strong>unique name</strong> (SimpleTaskSystem 
here). Thus, different sources (stored in different format and data sources) can be used in the application. XmlLocalizationSource also needs a folder (<strong>/Localization/SimpleTaskSystem</strong> 
here) to read localization files. </p>

<p>Then we can get localized texts when we need. In C#, we have two option to get a localizaed text:</p>

<pre lang="cs">
//Use directly
var s1 = LocalizationHelper.GetString(&quot;SimpleTaskSystem&quot;, &quot;NewTask&quot;);

//Use after get source
var source = LocalizationHelper.GetSource(&quot;SimpleTaskSystem&quot;);
var s2 = source.GetString(&quot;NewTask&quot;);
</pre>

<p>It returns the localized text in <strong>current language </strong>(by using CurrentUICulture of the current thread). There are also overrides to get text in a specific culture. There is a similar API in the javascript to get localized texts:</p>

<pre lang="js">
//Use directly
var s1 = abp.localization.localize(&#39;NewTask&#39;, &#39;SimpleTaskSystem&#39;);

//Use after get source
var source = abp.localization.getSource(&#39;SimpleTaskSystem&#39;);
var s2 = source(&#39;NewTask&#39;);
</pre>

<p>These methods also get the localized text in the <strong>current language</strong>.</p>

<h3 id="JavascriptApi">Javascript API</h3>

<p>There are some common functionallity every application needs in client side, in javascript. For example: to show a success notification, to block ui elements, to show a message box and so on. There are many libraries (jQuery plugins) exists for that. But all they have different APIs. ASP.NET Boilerplate defines some common APIs for such tasks. So, if you want to change notification plug-in later, you&#39;ll only implement a simple API. Also, jQuery plug-ins can directly implement ABP APIs. Instead of directly call plug-in&#39;s notification API, you can call ABP&#39;s notification API. Here, I&#39;ll explain some of the APIs.</p>

<h4>Logging API</h4>

<p>When you want to write some simple log in the client, you can use console.log(&#39;...&#39;) API as you know. But it&#39;s not supported by all browsers and your script may be broken. So, you should check it first. Also, you may want to write logs somewhere else. ABP defines safe logging functions:</p>

<pre lang="js">
abp.log.debug(&#39;...&#39;);
abp.log.info(&#39;...&#39;);
abp.log.warn(&#39;...&#39;);
abp.log.error(&#39;...&#39;);
abp.log.fatal(&#39;...&#39;);</pre>

<p>Also, you can change log level by setting abp.log.level to one of abp.log.levels (ex: abp.log.levels.INFO to do not write debug logs). These functions write logs to console by default. But you can override this behaviour easily.</p>

<h4>Notification API</h4>

<p>We love to show some fancy auto-disappearing notifications when something happens, like when an item is saved or a problem occured. ABP defines APIs for that:</p>

<pre lang="js">
abp.notify.success(&#39;a message text&#39;, &#39;optional title&#39;);
abp.notify.info(&#39;a message text&#39;, &#39;optional title&#39;);
abp.notify.warn(&#39;a message text&#39;, &#39;optional title&#39;);
abp.notify.error(&#39;a message text&#39;, &#39;optional title&#39;);</pre>

<p>Notification API is implemented by <strong>toastr </strong>library<strong> </strong>by default. You can implement it in your favourite notification library.</p>

<h4>MessageBox API</h4>

<p>Message API is used to show a message to the user. User clicks OK and closes message window/dialog. Examples:</p>

<pre>
abp.message.info(&#39;some info message&#39;, &#39;some optional title&#39;);
abp.message.warn(&#39;some warning message&#39;, &#39;some optional title&#39;);
abp.message.error(&#39;some error message&#39;, &#39;some optional title&#39;);</pre>

<p>It&#39;s not currently implemented. You can implement it to show a dialog or message box.</p>

<h4>UI Block API</h4>

<p>This API is used to block whole page or an element on the page. Thus, user can not click it. ABP API&#39;s are:</p>

<pre lang="js">
abp.ui.block(); //Block all page
abp.ui.block($(&#39;#MyDivElement&#39;)); //You can use any jQuery selection..
abp.ui.block(&#39;#MyDivElement&#39;); //..or directly selector
abp.ui.unblock(); //Unblock all page
abp.ui.unblock(&#39;#MyDivElement&#39;); //Unblock specific element</pre>

<h4>UI Busy API</h4>

<p>Sometime you may want to make some page/element busy. For example, you may want to block a form and show a busy indicator while submitting the form to the server. ABP provides APIs for that:</p>

<pre lang="js">
abp.ui.setBusy(&#39;#MyRegisterForm&#39;);
abp.ui.clearBusy(&#39;#MyRegisterForm&#39;);</pre>

<p><strong>setBusy </strong>can take a <strong>promise</strong> as second 
argument to automatically call clearBusy when promise completed. See <strong>newtask</strong> ViewModel in the sample project (and in the article) for usage.</p>

<h4>Others</h4>

<p>Other useful APIs will be added in the future to ABP to standardize common tasks. There are also some utility function for common usage (as abp.utils.formatString that works like string.Format in C#).</p>

<p>NOTE: If you want to implement these APIs, implement they in seperate files and include this seperate js file to your page after abp.js.</p>

<h2 id="ArticleMore">More</h2>

<h3 id="AbpModuleSystem">Module System</h3>

<p>ASP.NET Boilerplate is designed to be modular. It provides infrastructure to create common modules those can be used in different applications. A module can depend on other modules. An application is composed by modules. A module is an assembly that includes a module class derived from <strong>AbpModule</strong>. In the sample application explained in this article, all layers are defined as seperated modules. For example, application layer define a module like that:</p>

<pre lang="cs">/// &lt;summary&gt;
/// &#39;Application layer module&#39; for this project.
/// &lt;/summary&gt;
[DependsOn(typeof(SimpleTaskSystemCoreModule))]
public class SimpleTaskSystemApplicationModule : AbpModule
{
    public override void Initialize()
    {
        //This code is used to register classes to dependency injection system for this assembly using conventions.
        IocManager.RegisterAssemblyByConvention(Assembly.GetExecutingAssembly());

        //We must declare mappings to be able to use AutoMapper
        DtoMappings.Map();
    }
}
</pre>

<p>ASP.NET Boilerplate calls modules PreInitialize, Initialize and PostInitialize methods respectively on applicatin startup. If module A depends on module B, module B is initialized before module A. Exact order of all methods: PreInitialize-B, PreInitialize-A, Initialize-B, Initialize-A, PostInitialize-B and PostInitialize-A. This is true for all dependency graph.</p>

<p>Initialize is the method where dependency injection configuration should be placed. Here, you see this module registers all classes in it&#39;s assembly as conventional (see next section). Then it maps classes using AutoMapper library (it&#39;s specific to this application). This module also defines dependencies (application layer depends only domain (core) layer of the application).</p>

<h3 id="DependencyInjection">Dependency injection and conventions</h3>

<p>ASP.NET Boilerplate almost makes invisible of using the dependency injection system when you write your application by following <strong>best practices</strong> and some <strong>conventions</strong>. It automatically registers all <strong>Repositories</strong>, <strong>Domain Services</strong>, <strong>Application Services</strong>, <strong>MVC Controllers</strong> and <strong>Web API Controllers</strong> automatically. For example, you may have a IPersonAppService interface and a PersonAppService class that implements it:</p>

<pre lang="cs">
public interface IPersonAppService : IApplicationService
{
    //...
}

public class PersonAppService : IPersonAppService
{
    //...
}</pre>

<p>ASP.NET Boilerplate automatically registers it since it implements IApplicationService interface (It&#39;s just an empty interface). It&#39;s registered as transient (created instance per usage). When you inject (using constructor injection) IPersonAppService interface to a class, a PersonAppService object is created and passed into constructor automatically. See <a href="http://www.aspnetboilerplate.com/Pages/Documents/Dependency-Injection" target="_blank"> detailed documentation</a> on Dependency Injection and it&#39;s implementation in ASP.NET Boilerplate.</p>

<h2 id="AboutAngularSample">About Angularjs &amp; EntityFramework sample</h2>

<p>I authored an article &quot;<a href="http://www.codeproject.com/Articles/791740/Using-AngularJs-ASP-NET-MVC-Web-API-and-EntityFram">Using AngularJs, ASP.NET MVC, Web API and EntityFramework to build NLayered Single Page Web Applications</a>&quot; that explain the same sample application in Angular &amp; EntityFramework.</p>

<h2><span style="color: rgb(51, 51, 51); ">Summary</span></h2>

<p>In this article, I introduced a new application framework: ASP.NET Boilerplate. It&#39;s a starting point to develop modern web applications using best practices and most popular tools. Since it&#39;s pretty new, there may be some missing concepts. But it does not restrict you. You can get it a start point and buıild your application. It&#39;s new and being developed and extended. I&#39;m actively using it in my company in the production.</p>

<p>You can write bug reports, issues and feature requests to the github page (<a href="https://github.com/aspnetboilerplate/aspnetboilerplate/issues">https://github.com/aspnetboilerplate/aspnetboilerplate/issues</a>). Since it&#39;s an open source project, you can fork it and send pull requests to contribute to the ABP source code. I want it to be a start point for all we .NET developers, so, it will be good to develop it together.</p>

<h2 id="ArticleHistory">Article history</h2>

<ul>
	<li><strong>2014-11-02</strong>: Updated article and source codes for ABP 
	v0.4.1.</li>
	<li><strong>2014-09-06</strong>: Article completely revised and updated with sample application for ABP v0.3.2.</li>
	<li><strong>2014-07-26</strong>: Updated article and source codes for ABP v0.3.0.1.</li>
	<li><strong>2014-07-01</strong>: Added link to other article that explains AngularJs &amp; EntityFramework integration.</li>
	<li><strong>2014-06-16</strong>: Added Angularjs&amp;EntityFramework sample. Updated to ABP v0.2.3.</li>
	<li><strong>2014-06-09</strong>: Article and sample project updated to ABP v0.2.2.1</li>
	<li><strong>2014-05-22</strong>:<strong> </strong>Updated sample project to latest ABP version.</li>
	<li><strong>2014-05-20</strong>: Added sections to the article.</li>
	<li><strong>2014-05-13</strong>: Added details and sections to the article.</li>
	<li><strong>2014-05-08</strong>: Added details and sections to the article.</li>
	<li><strong>2014-05-05</strong>: First publish of the article.</li>
</ul>

<h2 id="References">References</h2>

<p>[1] ASP.NET Boilerplate official website: <a href="http://www.aspnetboilerplate.com">http://www.aspnetboilerplate.com</a><br />
[2] Book: &quot;<a href="http://www.amazon.com/Domain-Driven-Design-Tackling-Complexity-Software/dp/0321125215">Domain Driven Design: Tackling Complexity in the Heart of Software</a>&quot; by Eric Evans.<br />
[3] Martin Fowler&#39;s web site: <a href="http://martinfowler.com/">http://martinfowler.com</a><br />
[4] Fleunt Migrator: <a href="https://github.com/schambers/fluentmigrator">https://github.com/schambers/fluentmigrator</a><br />
[5] FluentNHibernate: <a href="http://www.fluentnhibernate">http://www.fluentnhibernate.org</a><br />
[6] AutoMapper: <a href="http://automapper.org/">http://automapper.org/r.org/</a><br />
[7] Durandaljs: <a href="http://durandaljs.com/">http://durandaljs.com/</a><br />
[8] Knockout.js: <a href="http://knockoutjs.com/">http://knockoutjs.com/</a></p>

<!-- END OF THE ARTICLE -->

</body>

</html>
